//
//  Route.swift
//  app路由
//
//  Created by zhaoguoteng on 2020/4/27.
//  Copyright © 2020 zhaoguoteng. All rights reserved.
//

import UIKit

struct Route: Codable {
    var rid: Int?
    var name: String?
    var url: String?
    var remark: String?
    var img: String?
    var date: Double?
    
    static func testRoutes() -> [Route]? {
        
        guard let jsonPath = Bundle.main.path(forResource: "route", ofType: "json") else {
            return nil
        }
        
        let jsonUrl = URL(fileURLWithPath: jsonPath)
        
        do {
            let jsonData = try Data(contentsOf: jsonUrl)
            return self .routes(jsonData: jsonData)
        } catch {
            fatalError(error.localizedDescription)
        }
    }
    
    static func routes(jsonData: Data?) -> [Route]? {
                
        guard let jsonData = jsonData else {
            return nil
        }
        
        do {
            let objc = try JSONSerialization.jsonObject(with: jsonData, options: [])
                        
            if let _ = objc as? [Any] {
                let routes = try JSONDecoder().decode([Route].self, from: jsonData)
                return routes
            } else if let _ = objc as? [String: Any] {
                let route = try JSONDecoder().decode(Route.self, from: jsonData)
                return [route]
            }
        } catch {
//            如果文本是一个url地址，也可以保存
            if let url = String(data: jsonData, encoding: .utf8) {
                let urlComponents = URLComponents(string: url)
                if let _ = urlComponents?.scheme {
                    return [Route(name: "待命名", url: url, date: Date().timeIntervalSince1970)]
                }
            }
            fatalError(error.localizedDescription)
        }
        
        return nil
    }
}
